import React, {Component} from 'react';
import {
  SafeAreaView,
  FlatList,
  StyleSheet,
  View,
  Text,
  StatusBar,
  ScrollView,
  KeyboardAvoidingView,
  Image,
  TouchableOpacity,
} from 'react-native';

import {
  Header,
  LearnMoreLinks,
  Colors,
  DebugInstructions,
  ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';

import {ListItem} from 'react-native-elements';
import {Actions} from 'react-native-router-flux';

import Api from '../Api';
import SearchBar from '../views/SearchBar';

export default class CustomerSelector extends Component {
  constructor(props) {
    super(props);
    this.state = {refreshing: false};
  }

  componentDidMount() {
    this.customerinfo('%');
  }

  customerinfo(code) {
    this.setState({refreshing: true});
    Api.customerinfo(code).then(data => {
      this.setState({
        data,
        refreshing: false,
      });
    });
  }

  handleChooseCustomer = item => {
    // 选择客户
    Actions.pop();
    setTimeout(() => {
      Actions.refresh({customer: item});
    }, 500);
  };

  render() {
    return (
      <View style={{flex: 1}}>
        <FlatList
          refreshing={this.state.refreshing}
          data={this.state.data}
          renderItem={({item}) => (
            <ListItem
              key={item.id}
              onPress={() => this.handleChooseCustomer(item)}
              bottomDivider>
              <ListItem.Content>
                <ListItem.Title>{item.customerName}</ListItem.Title>
                <ListItem.Subtitle>{item.address}</ListItem.Subtitle>
              </ListItem.Content>
            </ListItem>
          )}
          ListHeaderComponent={
            <SearchBar
              onChangeText={text => {
                this.setState({code: text});
              }}
              onSubmitEditing={() => {
                this.customerinfo(this.state.code);
              }}
              value={this.state.code}
              enablesReturnKeyAutomatically={true}
              returnKeyType="search"
            />
          }
          onRefresh={() => {
            // this.customerinfo(this.state.code);
          }}
        />
      </View>
    );
  }
}
